package cn.rongdao.jrkabao.ui.login;

import android.content.Context;
import android.text.InputType;
import android.view.View;
import android.widget.TextView;

import com.igexin.sdk.PushManager;
import com.mifengkong.frtools.app.FRApplication;
import com.mifengkong.frtools.http.request.callback.FRBaseObserver;
import com.mifengkong.frtools.ui.activity.FRStartActivity;
import com.mifengkong.frtools.util.FRSharedPreferences;
import com.mifengkong.frtools.util.FRString;
import com.mifengkong.frtools.util.FRToast;
import com.mifengkong.frwidget.titlebar.TitleBarUIComponent;
import com.mifengkong.greendao.bean.UserInfo;
import com.mifengkong.statistic.growingio.GIOUtils;
import com.mifengkong.statistic.talkingdata.TalkingData;

import butterknife.BindView;
import cn.rongdao.jrkabao.BuildConfig;
import cn.rongdao.jrkabao.R;
import cn.rongdao.jrkabao.base.BaseActivity;
import cn.rongdao.jrkabao.bean.login.UserBean;
import cn.rongdao.jrkabao.constant.SPConstant;
import cn.rongdao.jrkabao.dao.UserDao;
import cn.rongdao.jrkabao.model.login.LoginModel;
import cn.rongdao.jrkabao.ui.login.uicomponent.LoginBottomUIComponent;
import cn.rongdao.jrkabao.ui.login.uicomponent.LoginInputUIComponent;
import cn.rongdao.jrkabao.ui.main.MainActivity;
import cn.rongdao.jrkabao.ui.setting.SelectEnvironmentActivity;
import cn.rongdao.jrkabao.util.BigDecimalUtil;
import cn.rongdao.jrkabao.util.CommonUtil;
import cn.rongdao.jrkabao.util.GetDefaultDataUtil;
import io.reactivex.Observable;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function3;

/**
 * Created by jack on 2018/4/20
 */

public class LoginActivity extends BaseActivity implements View.OnClickListener {

    public static void start(Context context) {
        FRStartActivity.start(context, LoginActivity.class);
    }

    @BindView(R.id.al_titlebar)
    TitleBarUIComponent titleBarUIComponent;
    @BindView(R.id.al_phone_input)
    LoginInputUIComponent phoneInput;
    @BindView(R.id.al_password_input)
    LoginInputUIComponent passwordInput;
    @BindView(R.id.al_login_bottom)
    LoginBottomUIComponent loginBottomUIComponent;
    @BindView(R.id.al_tv_forget_password)
    TextView tvForgetPwd;
    @BindView(R.id.al_tv_old_user_enter)
    TextView tvOldUserEnter;

    private CompositeDisposable compositeDisposable;

    @Override
    protected int layoutRes() {
        return R.layout.activity_login;
    }

    @Override
    protected void initView() {
        compositeDisposable = new CompositeDisposable();

        initTitleBar();
        initListener();
        initUniqueId();
        initInput();
    }

    private void initInput() {
        phoneInput.setInputMaxLength(11);
        phoneInput.setInputType(InputType.TYPE_CLASS_PHONE);
        phoneInput.setHint("请输入手机号");
        phoneInput.initDelete();
        passwordInput.setInputMaxLength(20);
        passwordInput.setHint("请输入密码");
        passwordInput.setPassword();
        passwordInput.initDelete();

        compositeDisposable.add(Observable.combineLatest(phoneInput.getInputObservable(), passwordInput.getInputObservable(), loginBottomUIComponent.getCheckBoxObservable(), new Function3<CharSequence, CharSequence, Boolean, Boolean>() {
            @Override
            public Boolean apply(CharSequence phoneSequence, CharSequence passwordSequence, Boolean aBoolean) throws Exception {
                return !FRString.isEmpty(FRString.valueOf(phoneSequence), FRString.valueOf(passwordSequence)) && aBoolean;
            }
        }).subscribe(new Consumer<Boolean>() {
            @Override
            public void accept(Boolean aBoolean) throws Exception {
                loginBottomUIComponent.setLoginBtnEnable(aBoolean);
            }
        }));
    }

    private void initListener() {
        if (!FRString.isEmpty(FRSharedPreferences.getStringNotClear(SPConstant.IS_SHOW_UPDATE_POP, ""))) {
            FRSharedPreferences.setStringNotClear(SPConstant.IS_SHOW_UPDATE_POP, "");
            showDialogCheckUpdatePresenter();
        }
        tvForgetPwd.setOnClickListener(this);
        tvOldUserEnter.setOnClickListener(this);
        loginBottomUIComponent.setRegister();
        loginBottomUIComponent.setOnLoginClickListener("登录", new Consumer<Object>() {
            @Override
            public void accept(Object o) throws Exception {
                login();
            }
        });
    }

    private void login() {
        if (CommonUtil.checkPhone(phoneInput.getInputContent()) && CommonUtil.isPasswordCorrect(passwordInput.getInputContent())) {
            LoginModel.getInstance()
                    .addParams("phone", FRString.valueOf(phoneInput.getInputContent()))
                    .addParams("password", BigDecimalUtil.getMD5(passwordInput.getInputContent()))
                    .addParams("device_id", FRString.valueOf(getUniqueId()))
                    .addParams(GetDefaultDataUtil.getDefaultUserInfo(thisActivity()))
                    .execute(new FRBaseObserver<UserBean>(this, "正在登录，请稍候...") {
                        @Override
                        protected void onBaseNext(UserBean data) {
                            FRToast.showToastSafe("登录成功");
                            PushManager.getInstance().turnOnPush(thisActivity());
                            UserDao.getInstance().insertObject(new UserInfo(data.getUser_id(), phoneInput.getInputContent(), data.getToken()));
                            GIOUtils.setCS1(FRApplication.getInstance().getPackageName(), data.getUser_id());
                            TalkingData.onLogin(data.getUser_id());
                            TalkingData.onRegister(data.getUser_id());
                            MainActivity.Companion.start(thisActivity());
                            finish();
                        }
                    });
        }
    }

    private void initTitleBar() {
        titleBarUIComponent.initTitleBlack("登录");

        if (BuildConfig.DEBUG) {
            titleBarUIComponent.initRightBlack("网络请求设置", new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    SelectEnvironmentActivity.start(thisActivity());
                }
            });
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.al_tv_forget_password:
                RegisterActivity.startFromForgetPwd(thisActivity());
                break;
            case R.id.al_tv_old_user_enter:
                RegisterActivity.startFromSetPwd(thisActivity());
                break;
        }
    }

    @Override
    protected boolean useBlackStatusBarOnWhite() {
        return true;
    }

    @Override
    public void onDestroy() {
        phoneInput.onDestroy();
        passwordInput.onDestroy();
        loginBottomUIComponent.onDestroy();
        if (null != compositeDisposable) {
            compositeDisposable.dispose();
            compositeDisposable = null;
        }
        super.onDestroy();
    }
}
